package com.bill.app.action;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import com.bill.common.news.dto.NewsDetailDTO;
import com.bill.common.news.service.INewsService;
import com.bill.common.system.dto.AccountInfoDTO;
import com.bill.common.system.dto.DataDTO;
import com.bill.common.system.dto.ExtractDTO;
import com.bill.common.system.dto.SingleGroupReportStatDTO;
import com.bill.common.system.dto.TransactionRecordDTO;
import com.bill.common.system.service.IExtractService;
import com.bill.common.system.service.ITransactionRecordService;
import com.bill.common.user.dto.RegisterUserDTO;
import com.bill.common.user.dto.RegisterUserQueryDTO;
import com.bill.common.user.service.IAccountService;
import com.bill.common.user.service.IRegisterUserService;
import com.bill.common.utils.TranType;
import com.opensymphony.xwork2.ActionSupport;
import com.sinba.common.dto.PageDTO;

@SuppressWarnings("serial")
public class AppAction extends ActionSupport{
	@Autowired
	private IRegisterUserService registerUserService;
	@Autowired
	private ITransactionRecordService transactionRecordService;
	@Autowired
	private IExtractService extractService;
	@Autowired
	private IAccountService accountService;
	@Autowired
	private INewsService newsService;
	
	private static String valKey = "FD9E8WIW";
	
	private RegisterUserDTO registerUserDTO = new RegisterUserDTO();
	private RegisterUserQueryDTO registerUserQueryDTO = new RegisterUserQueryDTO();
	private ExtractDTO extractDTO = new ExtractDTO();
	private PageDTO pageDTO = new PageDTO();
	private TransactionRecordDTO trDTO = new TransactionRecordDTO();
	private NewsDetailDTO newsDetailDTO = new NewsDetailDTO();
	private AccountInfoDTO accountInfoDTO = new AccountInfoDTO();
	private DataDTO dataDTO = new DataDTO();
	
	private String loginName; 
	private String password;
	private String resultStr;
	private String key = "FD9E8WIW";
	private String recommendUser;
	private String bonusType;
	private String sord;
    private String sidx;
    private int page = 1;
    private int rows = 10;
    private String accountDype;
    private Double moeny;
    private String outLoginName;
    private String inLoginName;
    private String registerLocation;
    private String activeType = "Myself";
	

	public RegisterUserDTO getRegisterUserDTO() {
		return registerUserDTO;
	}

	public void setRegisterUserDTO(RegisterUserDTO registerUserDTO) {
		this.registerUserDTO = registerUserDTO;
	}

	public RegisterUserQueryDTO getRegisterUserQueryDTO() {
		return registerUserQueryDTO;
	}

	public void setRegisterUserQueryDTO(RegisterUserQueryDTO registerUserQueryDTO) {
		this.registerUserQueryDTO = registerUserQueryDTO;
	}

	public ExtractDTO getExtractDTO() {
		return extractDTO;
	}

	public void setExtractDTO(ExtractDTO extractDTO) {
		this.extractDTO = extractDTO;
	}

	public PageDTO getPageDTO() {
		return pageDTO;
	}

	public void setPageDTO(PageDTO pageDTO) {
		this.pageDTO = pageDTO;
	}

	public TransactionRecordDTO getTrDTO() {
		return trDTO;
	}

	public void setTrDTO(TransactionRecordDTO trDTO) {
		this.trDTO = trDTO;
	}

	public NewsDetailDTO getNewsDetailDTO() {
		return newsDetailDTO;
	}

	public void setNewsDetailDTO(NewsDetailDTO newsDetailDTO) {
		this.newsDetailDTO = newsDetailDTO;
	}

	public AccountInfoDTO getAccountInfoDTO() {
		return accountInfoDTO;
	}

	public void setAccountInfoDTO(AccountInfoDTO accountInfoDTO) {
		this.accountInfoDTO = accountInfoDTO;
	}

	public DataDTO getDataDTO() {
		return dataDTO;
	}

	public void setDataDTO(DataDTO dataDTO) {
		this.dataDTO = dataDTO;
	}

	public String getLoginName() {
		return loginName;
	}

	public void setLoginName(String loginName) {
		this.loginName = loginName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getResultStr() {
		return resultStr;
	}

	public void setResultStr(String resultStr) {
		this.resultStr = resultStr;
	}

	public String getKey() {
		return key;
	}

	public void setKey(String key) {
		this.key = key;
	}

	public String getRecommendUser() {
		return recommendUser;
	}

	public void setRecommendUser(String recommendUser) {
		this.recommendUser = recommendUser;
	}

	public String getBonusType() {
		return bonusType;
	}

	public void setBonusType(String bonusType) {
		this.bonusType = bonusType;
	}

	public String getSord() {
		return sord;
	}

	public void setSord(String sord) {
		this.sord = sord;
	}

	public String getSidx() {
		return sidx;
	}

	public void setSidx(String sidx) {
		this.sidx = sidx;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public int getRows() {
		return rows;
	}

	public void setRows(int rows) {
		this.rows = rows;
	}

	public String getAccountDype() {
		return accountDype;
	}

	public void setAccountDype(String accountDype) {
		this.accountDype = accountDype;
	}

	public Double getMoeny() {
		return moeny;
	}

	public void setMoeny(Double moeny) {
		this.moeny = moeny;
	}

	public String getOutLoginName() {
		return outLoginName;
	}

	public void setOutLoginName(String outLoginName) {
		this.outLoginName = outLoginName;
	}

	public String getInLoginName() {
		return inLoginName;
	}

	public void setInLoginName(String inLoginName) {
		this.inLoginName = inLoginName;
	}
	public String getRegisterLocation() {
		return registerLocation;
	}

	public void setRegisterLocation(String registerLocation) {
		this.registerLocation = registerLocation;
	}
	public String getActiveType() {
		return activeType;
	}

	public void setActiveType(String activeType) {
		this.activeType = activeType;
	}

	/**
	 * 会员登录
	 * @return
	 */
	public String login(){
		if(StringUtils.hasText(loginName) && StringUtils.hasText(password)){
			if(!valKey.equals(key)){
				resultStr = "Validation Failed"; 
			}else{
				resultStr = registerUserService.login(loginName, password);
			}
			if("success".equals(resultStr)){
				dataDTO.setStatus("Success");
				dataDTO.setMessage("Congratulations, your login is successful(恭喜，登录成功)!");
			}else{
				dataDTO.setStatus("Failure");
				dataDTO.setMessage("I'm sorry, logon failed, please check the account or password is correct(对不起，登录失败，请检查帐号或密码是否正确)!");
			}
		}else{
			dataDTO.setStatus("Failure");
			dataDTO.setMessage("传入的参数不正确!");
		}
		
		return "dataDTO";
	}
	
	/**
	 * 会员注册
	 * @return
	 */
	public String userReg(){
		if(!valKey.equals(key)){
			resultStr = "Validation Failed"; 
			dataDTO.setStatus("Failure");
		}else{
			resultStr = registerUserService.saveRegisterUserAuth(registerUserDTO);
			if("success".equals(resultStr)){
				resultStr = registerUserService.saveRegisterUser(registerUserDTO);
				if("system_error".equals(resultStr)){
					dataDTO.setStatus("Failure");
					resultStr = "System error, please try again later(系统错误，请稍候重新再试)!";
				}else{
					dataDTO.setStatus("Success");
				}
			}else{
				dataDTO.setStatus("Failure");
			}
		}
		dataDTO.setMessage(resultStr);
		return "dataDTO";
	}
	
	//系统自动找接点人
	public String autoFindContactNo(){
		if(StringUtils.hasText(recommendUser) && StringUtils.hasText(registerLocation)){
			//resultStr = registerUserService.findContactNo(recommendUser,registerLocation);
			dataDTO.setStatus("Success");
			dataDTO.setData(resultStr);
		}else{
			dataDTO.setStatus("Failure");
			dataDTO.setMessage("传入的参数不正确!");
		}
		
		return "dataDTO";
	}
	
	
	//现金币帐户.马币账户.总奖金
	public String findAccountInfo(){
		if(StringUtils.hasText(loginName)){
			Double dynamicAccount = transactionRecordService.findUserBalance(loginName, "Dynamic");
			Double staticAccount = transactionRecordService.findUserBalance(loginName, "static");
			TransactionRecordDTO dto = new TransactionRecordDTO();
			dto.setTransactionTypes(new String[]{TranType.RiFenHong,TranType.DuiPengJiang,TranType.LingDaoJiang,TranType.DaiShuJiang,TranType.ZhiTuiJiang});
			dto.setLoginName(loginName);
			dto.setInOrExp("income");
			List<SingleGroupReportStatDTO> sgrs =  transactionRecordService.statDtype(dto);
			Double dynamic = 0D;
			Double statics = 0D;
			for(SingleGroupReportStatDTO sdto : sgrs){
				if("Dynamic".equals(sdto.getGroupField())){
					dynamic = sdto.getAggField();
				}else if("Static".equals(sdto.getGroupField())){
					statics = sdto.getAggField();
				}
			}
			//购物积分
			Double totalBouns=dynamic+statics;
			
			accountInfoDTO.setDynamicAccount(dynamicAccount);
			accountInfoDTO.setStaticAccount(staticAccount);
			accountInfoDTO.setTotalBouns(totalBouns);
			dataDTO.setStatus("Success");
			dataDTO.setData(accountInfoDTO);
		}else{
			dataDTO.setStatus("Failure");
			dataDTO.setMessage("传入的参数不正确!");
		}
		
		return "dataDTO";
	}
	
	
	//个人信息
	public String findUserInfo(){
		
		if(StringUtils.hasText(loginName)){
			RegisterUserQueryDTO qdto = new RegisterUserQueryDTO();
			qdto.setLoginName(loginName);
			registerUserDTO = registerUserService.findRegisterUserByIdOrLoginName(qdto);
			registerUserDTO.setPassword1(null);
			registerUserDTO.setPassword2(null);
			registerUserDTO.setPassword3(null);
			registerUserDTO.setPasswordAnswer(null);
			registerUserDTO.setPasswordProblem(null);
			dataDTO.setStatus("Success");
			dataDTO.setData(registerUserDTO);
		}else{
			dataDTO.setStatus("Failure");
			dataDTO.setMessage("传入的参数不正确!");
		}
		return "dataDTO";
	}
	
	
	//我的团队
	public String findMyTeam(){
		int start = ( page - 1 ) * rows;
	    registerUserQueryDTO.setStart( start );
	    registerUserQueryDTO.setLimit( rows );
	    pageDTO = registerUserService.myTeamPager(registerUserQueryDTO, sord, sidx);
	    if(pageDTO!=null){
	    	pageDTO.setPage( page );
	    	pageDTO.setRows( rows );
	    }
	    dataDTO.setStatus("Success");
		dataDTO.setData(pageDTO);
		return "dataDTO";
	}
	
	//我的团队已激活数量
	public String getTeamActiveQuy(){
		Integer result = registerUserService.userCount(loginName,"TeamActivation",null);
		dataDTO.setStatus("Success");
		dataDTO.setData(result);
		return "dataDTO";
	}
	
	
	//提现
	public String withdraw(){
		if(extractDTO!=null && StringUtils.hasText(extractDTO.getLoginName()) && StringUtils.hasText(extractDTO.getDtype()) && extractDTO.getTixiangSum()!=null && extractDTO.getTixiangSum()>0){
			resultStr = extractService.apply(extractDTO);
			if(resultStr.indexOf("提现成功")!=-1){
				dataDTO.setStatus("Success");
			}else{
				dataDTO.setStatus("Failure");
			}
			dataDTO.setMessage(resultStr);
		}else{
			dataDTO.setStatus("Failure");
			dataDTO.setMessage("传入的参数不正确!");
		}
		
		return "dataDTO";
	}
	
	
	//提现历史记录
	public String withdrawHistory(){
		if(StringUtils.hasText(loginName)){
			int start = ( page - 1 ) * rows;
			extractDTO.setLoginName(loginName);
	        pageDTO = extractService.findPager( extractDTO, start, rows, sord, sidx );
	        if(pageDTO!=null){
		        pageDTO.setPage( page );
		        pageDTO.setRows( rows );
	        }
	        dataDTO.setStatus("Success");
			dataDTO.setData(pageDTO);
		}else{
			dataDTO.setStatus("Failure");
			dataDTO.setMessage("传入的参数不正确!");
		}
		
		return "dataDTO";
	}
	
	
	
	//转账
	public String exchange(){
		if(StringUtils.hasText(outLoginName) && StringUtils.hasText(inLoginName) && StringUtils.hasText(accountDype) && (moeny!=null && moeny>0)){
			resultStr=accountService.deltaTransfer(outLoginName,inLoginName, moeny,accountDype);
			if(resultStr.indexOf("转账成功")!=-1){
				dataDTO.setStatus("Success");
			}else{
				dataDTO.setStatus("Failure");
			}
			dataDTO.setMessage(resultStr);
		}else{
			dataDTO.setStatus("Failure");
			dataDTO.setMessage("传入的参数不正确!");
		}
		
		return "dataDTO";
	}
	
	
	//转账历史记录
	public String exchangeHistory(){
		int start = ( page - 1 ) * rows;
		trDTO.setStart( start );
		trDTO.setLimit( rows );
		trDTO.setTransactionTypes(new String[]{TranType.ZhuanZhang});
		trDTO.setLoginName(loginName);
        pageDTO = transactionRecordService.findTransactionRecordPager(trDTO, sord, sidx);
        if(pageDTO!=null){
	        pageDTO.setPage( page );
	        pageDTO.setRows( rows );
        }
        dataDTO.setStatus("Success");
		dataDTO.setData(pageDTO);
		return "dataDTO";
	}
	
	
	//奖金明细
	public String bonusDetails(){
		
		int start = ( page - 1 ) * rows;
		trDTO.setStart( start );
		trDTO.setLimit( rows );
		//动态奖金明细
		if("DynamicAwardDetails".equals(accountDype)){
			trDTO.setTransactionTypes(new String[]{TranType.DuiPengJiang,TranType.LingDaoJiang,TranType.ZhiTuiJiang,TranType.DaiShuJiang});
			trDTO.setSearchType("Dynamic");
			trDTO.setDtype("Dynamic");
		}
		//马币奖金明细
		if("MBAwardDetails".equals(accountDype)){
			trDTO.setTransactionTypes(new String[]{TranType.DuiPengJiang,TranType.LingDaoJiang,TranType.DaiShuJiang,TranType.ZhiTuiJiang});
			trDTO.setSearchType("Static");
			trDTO.setDtype("Static");
		}
		//静态奖金明细
		if("StaticAwardDetails".equals(accountDype)){
			trDTO.setTransactionTypes(new String[]{TranType.RiFenHong});
			trDTO.setSearchType("Static");
			trDTO.setDtype("Static");
		}
		//现金币帐户
		if("DynamicAccount".equals(accountDype)){
			trDTO.setTransactionTypes(null);
			trDTO.setSearchType("Dynamic");
			trDTO.setDtype("Dynamic");
		}
		
		//马币帐户
		if("StaticAccount".equals(accountDype)){
			trDTO.setTransactionTypes(null);
			trDTO.setSearchType("Static");
			trDTO.setDtype("Static");
		}
        pageDTO = transactionRecordService.findTransactionRecordPager(trDTO, sord, sidx);
        if(pageDTO!=null){
	        pageDTO.setPage( page );
	        pageDTO.setRows( rows );
        }
        dataDTO.setStatus("Success");
		dataDTO.setData(pageDTO);
		return "dataDTO";
	}
	
	
	//理财规则
	public String financingRule(){
		newsDetailDTO = newsService.findNewsByNewType("Rule");
		dataDTO.setStatus("Success");
		dataDTO.setData(pageDTO);
		return "dataDTO";
	}
	
	
	//会员激活
	public String userActivation(){
		if(StringUtils.hasText(loginName) && StringUtils.hasText(activeType)){
			resultStr = registerUserService.userActivate(loginName, activeType);
			if("success".equals(resultStr)){
				dataDTO.setStatus("Success");
				dataDTO.setMessage("Activation successful(激活成功)");
			}else{
				dataDTO.setStatus("Failure");
				if("AlreadyActivation".equals(resultStr)){
					dataDTO.setMessage("当前会员已激活,请检查!");
				}else if("balance".equals(resultStr)){
					dataDTO.setMessage("激活失败，请检查是否在足够的余额激活!");
				}
			}	
		}else{
			dataDTO.setStatus("Failure");
			dataDTO.setMessage("传入的参数不正确!");
		}
		return "dataDTO";
	}
	
	public String logout(){
		try {
			HttpSession session = ServletActionContext.getRequest().getSession();
			session.invalidate();
		} catch (Exception e) {
			// TODO: handle exception
		}
		dataDTO.setStatus("Success");
		dataDTO.setMessage("注销成功!");
		return "dataDTO";
	}
	
	//奖金统计
	public String bonusSum(){
		//动态奖金明细
		Double income = 0D;
		TransactionRecordDTO trDto1 = new TransactionRecordDTO();
		trDto1.setInOrExp("income");
		trDto1.setLoginName(loginName);
		//动态奖金明细
		if("DynamicAwardDetails".equals(accountDype)){
			trDto1.setDtype("Dynamic");
			trDto1.setTransactionTypes(new String[]{TranType.DuiPengJiang,TranType.LingDaoJiang,TranType.ZhiTuiJiang,TranType.DaiShuJiang});
		}
		
		//马币奖金明细
		if("MBAwardDetails".equals(accountDype)){
			trDto1.setTransactionTypes(new String[]{TranType.DuiPengJiang,TranType.LingDaoJiang,TranType.DaiShuJiang,TranType.ZhiTuiJiang});
			trDto1.setDtype("Static");
		}		
		
		//静态奖金明细
		if("StaticAwardDetails".equals(accountDype)){
			trDto1.setTransactionTypes(new String[]{TranType.RiFenHong});
			trDto1.setDtype(null);
		}
		
		//现金币帐户
		if("DynamicAccount".equals(accountDype)){
			trDto1.setTransactionTypes(null);
			trDto1.setDtype("Dynamic");
		}
		
		//马币帐户
		if("StaticAccount".equals(accountDype)){
			trDto1.setTransactionTypes(null);
			trDto1.setDtype("Static");
		}
		
		List<SingleGroupReportStatDTO> sgrs = transactionRecordService.statAccount(trDto1);
		for(SingleGroupReportStatDTO sgr : sgrs){
			if(sgr.getAggField()!=null){
				income = income+sgr.getAggField();
			}
		}
		dataDTO.setStatus("Success");
		dataDTO.setData(income);
		return "dataDTO";
	}
	
}
